package com.wutianyi.favority.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

import com.wutianyi.favority.FavorityRepository;
import com.wutianyi.favority.bean.User;
import com.wutianyi.favority.service.FavorityServiceLocator;
import com.wutianyi.favority.utils.FavorityUtils;

public class AddLinkServlet extends HttpServlet {

	/**
     * 
     */
	private static final long serialVersionUID = -2007910059301255893L;

	private static FavorityRepository repository = FavorityServiceLocator
			.getRepository();

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");

		long folderId = FavorityUtils.stringToLong(
				req.getParameter("folderId"), -1);
		long uid = FavorityUtils.stringToLong(req.getParameter("uid"), -1);
		String link = req.getParameter("link");

		System.out.println(link);

		if (-1 != folderId && -1 != uid && StringUtils.isNotBlank(link)) {
			User user = repository.getUser(uid);
			if (null != user) {
				int r = user.addLink(folderId, link);
				if (1 == r) {
					req.setAttribute("result", "添加成功");
				}
			}
		}
		resp.sendRedirect("linkIndex?uid=" + uid + "&folderId=" + folderId);
	}

	@Override
	public void destroy() {
		super.destroy();
		repository.getGraphDb().shutdown();
	}

}
